package alg

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func init() {
	RegisterAlgInfo(
		"longest-consecutive-sequence",
		AlgInfo{
			name: "最长连续序列",
			url:  "https://leetcode.cn/problems/longest-consecutive-sequence",
			alg: func() {
				reader := bufio.NewReader(os.Stdin)

				fmt.Print("请输入数字数组(用逗号分隔，例如 100,200,123): ")
				input, err := reader.ReadString('\n')
				if err != nil {
					fmt.Println("读取输入时发生错误:", err)
					return
				}
				input = strings.TrimSpace(input)
				if input == "" {
					fmt.Println("输入不能为空")
					return
				}

				numStrs := strings.Split(input, ",")
				nums := []int{}

				for _, numStr := range numStrs {
					num, err := strconv.Atoi(strings.TrimSpace(numStr))

					if err != nil {
						fmt.Printf("无效数字: %s\n", numStr)
					}
					nums = append(nums, num)
				}
				fmt.Println("输入的数字数组: ", nums)
				fmt.Println("最长连续序列长度: ", longestConsecutive(nums))
			},
		})
}

// 使用一个 map 数组存储每个数字, 遍历这个 map 数组按递增计数,计数最大的就是最长连续序列长度

func longestConsecutive(nums []int) int {
	numSet := make(map[int]bool)
	longestC := 0

	for _, num := range nums {
		numSet[num] = true
	}

	for num := range numSet {
		if !numSet[num-1] {
			currentNum := num
			currentC := 1
			for numSet[currentNum+1] {
				currentNum++
				currentC++
			}
			if currentC > longestC {
				longestC = currentC
			}
		}
	}

	return longestC
}
